#!/bin/sh

SKYPE="skype"
DBUS_SEND="dbus-send"
BUS="--system"
SKYPE_BUS=""
ID=`id -u`

print_help()
{
	cat << EOF
Skype "callto://" handler
 Usage: skype-callto-handler [BUS] callto://user
 Where BUS can be either "--system" (default) or "--session"
EOF
}

if [ -z "$1" -o "$1" = "--help" ]; then
	print_help
	exit 1
fi

if [ "--system" = "$1" -o "--session" = "$1" ];then
	BUS="$1"
	shift 1
fi

if [ "--session" = "$BUS" ]; then
	SKYPE_BUS="--use-session-dbus"
fi

if [ -z "$1" ];then
	print_help
	exit 1
fi

CALLTO=`echo $1 | sed 's/callto:\/\///'`

PING=`$DBUS_SEND $BUS --type=method_call --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ServiceExists string:com.Skype.API 2> /dev/null`; RESULT=$?

if [ $RESULT -ne 0 ]; then
	echo "ERROR: Failed to connect to DBUS daemon!"
	exit 1
fi

echo "$PING" | grep -q "boolean:true"; RESULT=$?

if [ $RESULT -ne 0 ]; then
	echo "Running Skype instance not found, launching"
	$SKYPE $SKYPE_BUS --callto "$CALLTO" &
	exit 0
fi

SKYPE_ID=`$DBUS_SEND $BUS --type=method_call --print-reply --dest=com.Skype.API /com/Skype com.Skype.API.Ping 2> /dev/null`;RESULT=$?

if [ $RESULT -ne 0 ]; then
	echo "ERROR: Skype is running on specified bus, but is misbehaving!"
	exit 1
fi

TEMP=`echo "$SKYPE_ID" | grep -o "int32:[0-9]*"`

SKYPE_ID=`echo "$TEMP" | cut -f2 -d':'`

if [ $ID -ne $SKYPE_ID ]; then
	echo "ERROR: Skype is running on specified bus, but for different UNIX user!"
	exit 1
fi

REPLY=`$DBUS_SEND $BUS --type=method_call --print-reply --dest=com.Skype.API /com/Skype com.Skype.API.Invoke string:CALL\ $CALLTO 2> /dev/null`;RESULT=$?

if [ $RESULT -ne 0 ]; then
	echo "ERROR: Error when communicating with Skype!"
	exit 1
fi

TEMP=`echo "$REPLY" | grep -o "string:.*"`

REPLY=`echo "$TEMP" | cut -f2 -d':'`

echo $REPLY

exit 0
